/***********************************************************************************
**  
* @copyright (c) 2010-2019, ChengDu Duyer Technology Co., LTD. All Right Reserved.
*
************************************************************************************/
/**
* @file	    mjs_hb_action.cpp
* @version     
* @brief      
* @author   duye
* @date	    2016-12-26
* @note 
*
* 1. 2016-12-26 duye Created this file
*/

#include <duye_type.h>
#include <duye_logger.h>
#include <duye_cfg_mgr.h>
#include <mj_net_protocol.h>
#include <mjs_reqer.h>
#include <mjs_hb_action.h>

static const int8* DUYE_LOG_PREFIX = "mangjings.action.heartbeat";

MJSHBAction::MJSHBAction() {}
MJSHBAction::~MJSHBAction() {}

bool MJSHBAction::onAction(MJMsgAction* action, MJSReqer* reqer) {
	if (!action || !reqer) {
		DUYE_ERROR("action == NULL || reqer == NULL");
		return false;
	}

	if (action->getName() != "heartbeat") {
		DUYE_ERROR("action_name != 'heartbeat");
		return false;		
	}

	std::string client_ip = action->getValue("ip");
	DUYE_TRACE("receivec client=%s heartbeat message", client_ip.c_str());
	if (client_ip != reqer->getIP()) {
		DUYE_ERROR("client ip unmath, heartbeat_ip=%s, client_proxy_ip=%s, will disconnet", client_ip.c_str(), reqer->getIP().c_str());
		// notify client proxy
		if (!reqer->notify(MJS_INNER_DISCONNECT)) {
			DUYE_ERROR("send innerNotify(MJS_INNER_DISCONNECT) failed");
			return false;
		}

		return true;
	}
	
	// response client
	MJMsgAction resp_action;
	if (!MJMsgFactory::ins().createAction(action->getName(), resp_action)) {
		DUYE_ERROR("createAction 'auth' failed");
		return false;
	}
	
	resp_action.setValue("ip", client_ip);
	std::string expire;
	if (!duye::CfgMgr::ins().getValue("node:global.param:heartbeat", expire, "value")) {
		DUYE_ERROR("get node:global.param:heartbeat faield");
		return false;
	}
	resp_action.setValue("expire", expire);

	MJSInnerMsgType msg_type = MJS_INNER_UPCONNECT;
	std::string msg_xml;
	MJMsgFactory::ins().createMsgXml(resp_action, msg_xml);
	if (!reqer->sendToClient(msg_xml)) {
		DUYE_WARN("send heartbeat to %s failed, will disconnet", client_ip.c_str());
		msg_type = MJS_INNER_DISCONNECT;
	} else {
		DUYE_INFO("send heartbeat to %s ok", client_ip.c_str());
	}

	// notify client proxy
	if (!reqer->notify(msg_type)) {
		DUYE_ERROR("send innerNotify(%d) failed", msg_type);
		return false;
	}

	return true;
}